import * as vscode from 'vscode'
import { toString } from 'qrcode'

export function activate(context: vscode.ExtensionContext) {
	// 生成二维码
	context.subscriptions.push(vscode.commands.registerCommand('gqr-plugin.gqr', async () => {
		const msg = await vscode.window.showInputBox({ title: "输入要生成二维码的内容" })
		if (!msg) return
		const content = await toString(msg)
		if (!content) return
		const doc = await vscode.workspace.openTextDocument({ content })
		vscode.window.showTextDocument(doc)
	}))

	// 格式化选中内容的json
	context.subscriptions.push(vscode.commands.registerCommand('gqr-plugin.formatJson', async () => {
		const editor = vscode.window.activeTextEditor
		if (editor) {
			const document = editor.document
			const selection = editor.selection
			// 获取选中的文本
			const text = document.getText(selection)
			try {
				// 解析JSON
				const json = JSON.parse(text)
				// 格式化JSON
				const formattedJson = JSON.stringify(json, null, 4)
				// 替换选中的文本
				editor.edit(editBuilder => {
					editBuilder.replace(selection, formattedJson)
				}).then(success => {
					if (success) {
						vscode.window.showInformationMessage('JSON格式化完成')
					} else {
						vscode.window.showErrorMessage('JSON格式化失败')
					}
				})
			} catch (error: SyntaxError | any) {
				vscode.window.showErrorMessage(`选中JSON格式有误: ${error.message}`)
			}
		}
	}))
}

export function deactivate() { }
